package com.heima.controller;

import com.heima.common.PageResult;
import com.heima.pojo.AliyunOssProperties;
import com.heima.pojo.Sku;
import com.heima.pojo.dto.SkuClassPageQueryDTO;
import com.heima.pojo.vo.SkuVo;
import com.heima.service.SkuService;
import com.heima.utils.AliyunOSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/vm-service/sku")
public class SkuController {

    @Autowired
    private AliyunOssProperties aliyunOssProperties;
    @Autowired
    private SkuService skuService;

    @PostMapping("/fileUpload")
    public String upload(MultipartFile fileName) throws Exception {
        log.info("文件上传--------------{}", fileName);
        String extName = fileName.getOriginalFilename().substring(fileName.getOriginalFilename().lastIndexOf("."));
        String url = AliyunOSSUtils.upload(aliyunOssProperties.getEndpoint(), aliyunOssProperties.getBucketName(), fileName.getBytes(), extName);
        log.info("图片的url------------------{}",url);
        return url;
    }

    @PostMapping
    public Boolean add(@RequestBody Sku sku){
        log.info("新增商品：{}",sku);
        sku.setCreateTime(LocalDateTime.now());
        sku.setUpdateTime(LocalDateTime.now());
        return skuService.add(sku);
    }

    @GetMapping("/search")
    public PageResult skuQuery(SkuClassPageQueryDTO dto){
        log.info("商品搜索：{}",dto);
        return skuService.skuQuery(dto);
    }

    @GetMapping("/{skuId}")
    public Sku findById(@PathVariable String skuId){
        log.info("根据id查询：{}",skuId);
        return skuService.findById(skuId);
    }

    @PutMapping("/{skuId}")
    public Boolean update(@PathVariable String skuId,@RequestBody Sku sku){
        log.info("修改商品：{},{}",skuId,sku);
        return skuService.update(skuId,sku);
    }

    @GetMapping("/businessTop10/{businessId}")
    public List<SkuVo> businessTop10(@PathVariable Integer businessId){
        log.info("获取商圈下销量前10的商品：{}",businessId);
        return skuService.businessTop10(businessId);
    }

}
